<template>
  <com-page class="com-color-content-bg com-spacing">
    <u-navbar :title="$t('pages_account_login_components_wx-login_msg_d72d86a5')" autoBack fixed placeholder />
    <view class="com-section com-spacing com-flex-col com-items-center com-mb-lg">
      <u-avatar class="com-mb-sm" src="@/static/images/logo.png" size="120" />
      <view class="com-text-lg">微信授权</view>
    </view>

    <view class="com-text-md com-mt-md">登录后该应用将获的以下权限</view>
    <view class="com-text-sm com-mb-md"
      >获得你的公开信息（{{ token && !userInfo.mobile ? '手机号码' : '昵称、头像等' }}）</view
    >
    <button
      v-if="!token"
      open-type="getUserInfo"
      @getuserinfo="getUserInfo"
      class="com-button com-block com-color-primary-bg com-round com-mt-lg"
      >微信授权
    </button>

    <button
      v-if="token && !userInfo.mobile"
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumber"
      class="com-button com-block com-color-primary-bg com-rounded-full com-mt-lg"
      >手机号授权
    </button>
  </com-page>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'App-Login',
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      token: (state) => state.user.token,
    }),
  },
  methods: {
    getUserInfo(res) {
      console.log('res :>> ', res)
      if (res.detail.errMsg == 'getUserInfo:fail auth deny') {
        this.$utils.toast('授权失败！请稍后再试', 'error')
        return
      }
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          console.log('loginRes :>> ', loginRes)
          if (loginRes.code) {
            uni.getUserInfo({
              provider: 'weixin',
              success: (infoRes) => {
                let params = {
                  encryptedData: infoRes.encryptedData,
                  iv: infoRes.iv,
                  code: loginRes.code,
                }
                this.$api.user.login(params).then((res) => {
                  this.$utils.toast(res.msg)
                  this.$store.dispatch('setToken', res.token)
                  this.$store.dispatch('setUserInfo', res.userInfo)
                  uni.navigateBack({
                    delta: 1,
                  })
                })
              },
            })
          }
        },
      })
    },
    getPhoneNumber(res) {
      let params = {
        code: this.code,
        iv: res.detail.iv,
        encryptedData: encodeURIComponent(res.detail.encryptedData),
      }
      this.$api.user.login(params).then((res) => {
        this.$utils.toast(res.msg)
        this.$store.dispatch('setToken', res.token)
        this.$store.dispatch('setUserInfo', res.data.userInfo)
        uni.navigateBack({
          delta: 1,
        })
      })
    },
    onShow() {
      uni.login({
        success: (res) => {
          if (res.code) {
            this.code = res.code
          }
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
